package junior.db.dao.update;

import junior.db.dao.base.MybatisHelper;
import junior.db.dao.base.IEntityWrapper;
import junior.db.dao.base.IExecuteAware;
import junior.db.dao.base.INamespaceAware;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wubo
 * @date 2024/8/29 13:36
 */
public abstract class AbstractInsertOption<O> implements IEntityWrapper, INamespaceAware, IExecuteAware {
    protected String namespace;
    protected Class<?> entityClass;
    protected String[] insertFields;
    protected String[] excludeFields;
    protected Map<String, String> insertFieldExpressionMap;
    private String[] generateKeyFields;
    
    public String getTable() {
        return MybatisHelper.getTable(namespace, this.entityClass);
    }
    
    @Override
    public Class<?> getEntityClass() {
        return entityClass;
    }
    
    public String[] getInsertFields() {
        return insertFields;
    }
    
    public String getColumn(String field) {
        return MybatisHelper.field2Column(namespace, entityClass, field);
    }
    
    public String[] getGenerateKeyFields() {
        return generateKeyFields;
    }
    
    /**
     * 指定值为自动生成的字段
     * @param fields
     * @return
     */
    public O withGenerateKeyFields(String... generateKeyFields) {
        Assert.notEmpty(generateKeyFields, "Parameter generateKeyFields is required");
        this.generateKeyFields = generateKeyFields;
        return (O) this;
    }
    
    /**
     * 指定要插入的字段
     * @param fields
     * @return
     */
    public O withInsertFields(String... fields) {
        Assert.notEmpty(fields, "Parameter fields is required");
        this.insertFields = fields;
        return (O) this;
    }
    
    public O withInsertExpression(String field, String expression) {
        if (insertFieldExpressionMap == null) {
            insertFieldExpressionMap = new HashMap<>();
        }
        insertFieldExpressionMap.put(field, expression);
        return (O) this;
    }
    
    /**
     * 指定排除插入的字段
     * @param ignoreFields 指定的字段不会被插入
     * @return
     */
    public O excludeInsertFields(String... ignoreFields) {
        Assert.notEmpty(ignoreFields, "Parameter ignoreFields is required");
        this.excludeFields = ignoreFields;
        return (O) this;
    }
    
    @Override
    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }
    
    @Override
    public String getNamespace() {
        return namespace;
    }
}
